package com.zt.aspect;

import com.zt.mapper.OperateLogMapper;
import com.zt.pojo.Emp;
import com.zt.pojo.EmpLoginLog;
import com.zt.pojo.Logininfo;
import com.zt.pojo.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Aspect
public class LoginAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.zt.anno.LoginOperation)")
    public Object loginLog(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = null;
        String jwt = null;
        Short success = null;
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            jwt = "登录失败，没有token";
            throw e;
        } finally {
            long end = System.currentTimeMillis();
            Result res = (Result) result;
            if(res == null){
                success = (short) 0;
            }else {
                success = res.getCode() == 1 ? (short) 1 : (short) 0;
                Logininfo info = (Logininfo) res.getData();
                if (success == 1) {
                    jwt = info.getToken();
                }
            }
            Emp emp = (Emp) pjp.getArgs()[0];
            EmpLoginLog empLoginLog = EmpLoginLog.builder()
                    .username(emp.getUsername())
                    .password(emp.getPassword())
                    .loginTime(LocalDateTime.now())
                    .isSuccess(success)
                    .jwt(jwt)
                    .costTime(end - start)
                    .build();
            operateLogMapper.insertlogin(empLoginLog);
        }
        return result;
    }
}
